#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <signal.h> 
#include <pthread.h>

#include "log.hpp"


namespace Server
{
    // using namespace std;

    static const uint16_t gport = 8080;
    static const int gbacklog = 5;

    class tcpServer;//声明
    class threadData
    {
    public:
        threadData(tcpServer* self,const int& sock)
            :_self(self),_sock(sock)
        {}
    public:
        tcpServer* _self;
        int _sock;
    };
    class tcpServer
    {
    public:
        tcpServer(const uint16_t& port = gport)
            :_listensock(-1),_port(port)
        {}
        void initServer()
        {
            //1.创建socket文件套接字对象
            _listensock = socket(AF_INET,SOCK_STREAM,0);
            if(_listensock < 0)
            {
                logMessage(FATAL,"create socket error");
                exit(SOCKET_ERR);
            }
            logMessage(NORMAL,"create socket success");

            // 2.bind 绑定自己的网络信息
            struct sockaddr_in local;
            memset(&local,0,sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            local.sin_addr.s_addr = INADDR_ANY;
            if(bind(_listensock,(struct sockaddr*)&local,sizeof(local)) < 0)
            {
                logMessage(FATAL,"bind socket error");
                exit(BIND_ERR);
            }
            logMessage(NORMAL,"bind socket success");

            //3. 设置socket为监听状态
            if(listen(_listensock,gbacklog) < 0)
            {
                logMessage(FATAL,"listen socket error");
                exit(LISTEN_ERR);
            }
            logMessage(NORMAL,"listen socket success");

        }
        void start()
        {
            for( ; ; )  //死循环
            {
                //4. Server获取新链接
                //sock 是用于和client进行通信的
                struct sockaddr_in peer;
                socklen_t peer_len = sizeof(peer);
                int sock = accept(_listensock,(struct sockaddr*)&peer,&peer_len);
                if(sock < 0)
                {
                    logMessage(ERROR,"accept error,next");
                    continue;
                }
                logMessage(NORMAL,"accept a new link success");
                cout << "sock: " << sock <<endl;
                //5. 未来通信就用这个sock，面向字节流的，后面全是文件操作
                // version 1
                // serviceIO(sock);
                // close(sock);    //对于一个已经使用完毕的sock，我们需要关闭它，不然会导致文件描述符泄漏
                // //------------------------------------------------------------------------------------
                // //version 2.1 多进程版
                // pid_t id = fork();
                // if(id == 0) //子进程
                // {
                //     close(_listensock);
                //     if(fork() > 0) exit(0); //让孙子进程执行代码，子进程退出被父进程回收，孙子进程会变成孤儿进程

                //     serviceIO(sock);
                //     close(sock);
                //     exit(0);
                // }
                // //父进程
                // pid_t ret = waitpid(id,nullptr,0);
                // close(sock);
                // if(ret > 0)
                // {
                //     cout << "wait success: " << ret << endl;
                // }
                // //------------------------------------------------------------------------------------
                // //version 2.2 多进程版 信号方式
                // signal(SIGCHLD,SIG_IGN);    //信号忽略，忽略对子进程的管理

                // pid_t id = fork();
                // if(id == 0) //子进程
                // {
                //     close(_listensock);

                //     serviceIO(sock);
                //     close(sock);
                //     exit(0);
                // }
                // close(sock);
                // //------------------------------------------------------------------------------------
                // //version 3 多线程版
                pthread_t tid;
                threadData* td = new threadData(this, sock);
                pthread_create(&tid,nullptr,thread_routinue,td);    //创建线程

                
            }
        }
       
        static void* thread_routinue(void* args)
        {
            pthread_detach(pthread_self());//线程分离
            threadData* td = static_cast<threadData*>(args);
            td->_self->serviceIO(td->_sock);
            delete td;
            close(td->_sock);

            return nullptr;
        }
        void serviceIO(int sock)
        {
            char buffer[1024];
            while(true)
            {
                //暂时把读到的数据当字符串
                ssize_t n = read(sock,buffer,sizeof(buffer)-1);
                if(n > 0)
                {
                    buffer[n] = 0;
                    cout << "recv message: " << buffer << endl;
                    
                    string outbuffer = buffer;
                    outbuffer += " server[echo]";
                    write(sock,outbuffer.c_str(),outbuffer.size()); //多路转接
                }
                else if(n == 0)
                {
                    // 代表Client退出
                    logMessage(NORMAL,"client quit,me to!");
                    break;
                }
            }
        }
         
        ~tcpServer()
        {}
    private:
        int _listensock;    //不是用来数据通信的，它是监听链接是否到来的，用于获取新链接的
        uint16_t _port;
    } ;
    
}//namespace end Server 
